package com.sinochem.yunlian.ship.common.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.sinochem.yunlian.ship.api.vo.uc.AutenticationInfo;
import com.sinochem.yunlian.ship.common.annotation.NoAc;
import com.sinochem.yunlian.ship.common.enums.AutenticationType;
import com.sinochem.yunlian.ship.common.enums.CompanyStatus;
import com.sinochem.yunlian.ship.common.enums.CompanyType;
import com.sinochem.yunlian.ship.common.enums.ResponseCode;
import com.sinochem.yunlian.ship.common.exception.BaseException;

/**
 * 认证过滤
 */
@Component
public class AutenticationFilter extends HandlerInterceptorAdapter{

   /**
    * 
    * @param request
    * @param handler
    * @return
    */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		
		NoAc noAutentication = handlerMethod.getBeanType().getAnnotation(NoAc.class);
		
        if (noAutentication == null) {
        	noAutentication = handlerMethod.getMethodAnnotation(NoAc.class);
        }
		
		if (noAutentication != null) {
			
			if (!noAutentication.acUser() || noAutentication.noAcCompany()) {
				return super.preHandle(request, response, handler); 
			}
		}
		
		AutenticationService autenticationService = SpringContextAware.getBean("autenticationService");
		
		String userId = request.getHeader("currentUserId");
		
		if (StringUtils.isEmpty(userId)) {
			throw BaseException.message(ResponseCode.INVALID_TOKEN.getName(),ResponseCode.INVALID_TOKEN.getCode());                
		}
		// 认证返回信息
		AutenticationInfo acInfo = autenticationService.getAutenticationInfo(Long.valueOf(userId));
		
		if (acInfo == null) {
		   // 用户身份不存在
		   throw BaseException.message(ResponseCode.AUTH_USER_FAIL.getName(), ResponseCode.AUTH_USER_FAIL.getCode());
		}
		AutenticationInfo.AutenticatUser acUser = acInfo.getAcUser();
		
		AutenticationInfo.AutenticatCompany acCompany = acInfo.getAcCompany();
		
		if (acCompany != null && CompanyStatus.PASS.getCode() == acCompany.getAcCompanyStatus()) {
			// 用户通过公司认证
			return super.preHandle(request, response, handler); 
		}
		if (acUser == null) {
			 // 用户身份不存在
			throw BaseException.message(ResponseCode.AUTH_USER_FAIL.getName(), ResponseCode.AUTH_USER_FAIL.getCode());
		}
		if (acCompany == null) {
			// 未认证公司
			throw BaseException.message(ResponseCode.UN_AUTH.getName(), ResponseCode.UN_AUTH.getCode());
		}
		// 申请公司认证类型 
		if (AutenticationType.AC_COMPANY.getCode() == acCompany.getAcType()) {
			// 申请公司认证类型 --审核中
			if (CompanyStatus.CHECKING.getCode() == acCompany.getAcCompanyStatus()) {
				throw BaseException.message(ResponseCode.AUTH_AUDIT.getName(), ResponseCode.AUTH_AUDIT.getCode());
			}
			// 申请公司认证类型 --失败
			if (CompanyStatus.FAIL.getCode() == acCompany.getAcCompanyStatus()) {
				throw BaseException.message(ResponseCode.AUTH_FAIL.getName(), ResponseCode.AUTH_FAIL.getCode());
			}
		}
		// 加入公司认证类型
		if (AutenticationType.AC_JOIN_COMPANY.getCode() == acCompany.getAcType()) {
			
			String content  = null;
			
			// 加入公司认证类型 --审核中
			if (CompanyStatus.CHECKING.getCode() == acCompany.getAcCompanyStatus()) {
				content = "您申请加入" + acCompany.getCompanyName() + "的申请已经发送至管理员（" + acCompany.getCompanyAdminPhone() + "），等待管理员审核。";
				throw BaseException.message(content, ResponseCode.WAITING_MANAGER_ACCEPT.getCode());
			}
			// 加入公司认证类型 --拒绝
			if (CompanyStatus.FAIL.getCode() == acCompany.getAcCompanyStatus()) {
				
				if (CompanyType.CARGO.getCode() == acCompany.getCompanyType()) {
					content = "管理员（" + acCompany.getCompanyAdminPhone() + "）已经拒绝您的申请，您可以重新申请加入货主或者认证货主。";
				}
				if (CompanyType.SHIP.getCode() == acCompany.getCompanyType()) {
					content = "管理员（" + acCompany.getCompanyAdminPhone() + "）已经拒绝您的申请，您可以重新申请加入船东或者认证船东。";
				}
				
				throw BaseException.message(content, ResponseCode.MANAGER_REJECT_USER_JOIN_COMPANY.getCode());
			}
			
		}
		return super.preHandle(request, response, handler); 
	}

}
